package gw.com.android.ui.onlive.analyst;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gwtsz.gts2.hx.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.DiscussRequest;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.ImageOperationPopWindow;
import gw.com.android.ui.onlive.DiscussData;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.IOUtils;
import gw.com.android.utils.NetUtil;
import gw.com.android.utils.PackStatis;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.interfaces.ReqCallBack;
import www.com.library.view.XRecyclerView;

/**
 * 分析师个人点评
 *
 * @author jett
 * @since 2018-06-05.
 */
public class ReplyFragment extends Fragment {

    protected boolean isVisible;
    private boolean isPrepared = false;
    private LinearLayout ll_no_content;
    private LinearLayout ll_error;
    private TextView tv_no_content;
    private AnalystReplyAdapter analystReplyAdapter;
    private XRecyclerView mListView;
    private DiscussRequest request;
    private ImageWatcher imageWatcher;//图片放大工具
    private String accountNo;

    public void setAccountNo(String userNo) {
        this.accountNo = userNo;
    }

    public void setImageWatcher(ImageWatcher imageWatcher) {
        this.imageWatcher = imageWatcher;
    }

    /**
     * 长按图片 ，保存图片
     */
    private class LongPressListener implements ImageWatcher.OnPictureLongPressListener {
        @Override
        public void onPictureLongPress(ImageView v, final String url, int pos) {
            new ImageOperationPopWindow(getActivity(), new ImageOperationPopWindow.OnSaveListener() {
                @Override
                public void onSave() {
                    saveImage(url);
                }
            }).show();
        }
    }

    private void saveImage(String url) {
        final BaseActivity activity = (BaseActivity) getActivity();
        if (activity == null) {
            return;
        }
        activity.showLoading();

        String fileName = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
        final File file = new File(GTConfig.instance().getRootDirectory() + "/image/" + fileName + ".jpg");

        Glide.with(this).load(url).downloadOnly(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                activity.hideLoading();
                if (resource != null && resource.length() > 0) {
                    boolean copy = IOUtils.copy(resource, file);
                    if (copy) {
                        Uri uri = Uri.fromFile(file);
                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                        new ToastPopWindow(activity, AppMain.getAppString(R.string.home_save_success_title)).show();
                        return;
                    }
                }
                new ToastPopWindow(activity, AppMain.getAppString(R.string.home_save_fail_title)).show();
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                activity.hideLoading();
                new ToastPopWindow(activity, AppMain.getAppString(R.string.home_save_fail_title));
            }
        });
    }

    /**
     * 这里会多次执行
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        isPrepared = true;//如果是onCreateView先执行，这里也不会加载数据，因为isVisible是false。只有两个变量同时为true的时候，才会执行数据加载
        View root = inflater.inflate(R.layout.fragment_analyst_post, container, false);
        mListView = (XRecyclerView) root.findViewById(R.id.list_view);
        ll_error = (LinearLayout) root.findViewById(R.id.ll_error);
        ll_no_content = (LinearLayout) root.findViewById(R.id.ll_no_content);
        ll_no_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData();
            }
        });
        tv_no_content = (TextView) root.findViewById(R.id.tv_no_content);
        tv_no_content.setText("暂无点评");
        mListView.setLayoutManager(new LinearLayoutManager(getContext()));
        mListView.hideFooter();
        showListView();
        setEmptyView(mListView);
        onLazyLoad();
        return root;
    }

    /**
     * 这个方法只能作为一个标志位方法，用来标记当前fragment是不是可见，千万不要用它直接参与组件的创建和维护，因为在这个方法里面，调用getActivity有可能是空。
     * <p>
     * 为什么可能是空？因为，这个方法的调用，可能处于Fragment的生命周期之外。fragment还没创建好，它就开始了调用，你在这里调用getActivity，当然可能是空.
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            PackStatis.getToService("clickComments", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
            isVisible = true;//这个方法和onCreateView存在先后顺序，如果这个方法先，那么isVisible就会先变成true，但是这个时候，isPrepared还不是true，所以，懒加载不会进行。而要等到onCreateView执行的时候。
            onLazyLoad();
        } else {
            isVisible = false;
        }
    }

    private void onLazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        isPrepared = false;
        analystReplyAdapter = new AnalystReplyAdapter(getActivity());
        analystReplyAdapter.setWatcher(imageWatcher);
        imageWatcher.setOnPictureLongPressListener(new LongPressListener());
        mListView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData();
            }

            @Override
            public void onLoadMore() {
                nextPage();
            }
        });
        // 如果触发了数据加载，第一件事是来看看缓存内有没有数据
        fetchLocalData();
        mListView.setRefreshing(true);
    }

    private void fetchLocalData() {
        if (null == request) {
            request = new DiscussRequest();
        }
        List<DiscussData> cacheList = request.fetchLocal(DiscussRequest.TRADE_TYPE_REPLY, accountNo);
        if (cacheList != null && !cacheList.isEmpty()) {
            toastWhenFirstLoad();
            refreshUi(cacheList);
        }
    }


    private void loadData() {
//        if (null == request) {
//            request = new DiscussRequest();
//        }
        request.getList(new ReqCallBack<List<DiscussData>>() {
            @Override
            public void onReqSuccess(List<DiscussData> result) {
                mListView.refreshComplete();
                refreshUi(result);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                mListView.refreshComplete();
                onFailed();
            }
        }, DiscussRequest.TRADE_TYPE_REPLY, accountNo);
    }

    /**
     * 加载更多
     */
    private void nextPage() {
        if (request == null) {
            request = new DiscussRequest();
        }
        request.nextPage(new ReqCallBack<List<DiscussData>>() {
            @Override
            public void onReqSuccess(List<DiscussData> result) {
                mListView.loadMoreComplete();
                mListView.setNoMore(!request.hasNextPage());
                analystReplyAdapter.addData(result);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                mListView.loadMoreComplete();
                //mListView.setNoMore(false);
                onFailed();
            }
        });
    }

    private boolean ifDataAdapter = false;// 用一个变量标记，当前是否使用了数据adapter

    private void refreshUi(List<DiscussData> result) {
        //创建adapter，然后
        if (result != null && result.size() != 0) {
            if (!ifDataAdapter) {
                mListView.setAdapter(analystReplyAdapter);
                ifDataAdapter = true;
            }
            analystReplyAdapter.setData(result);
            showListView();
        } else {
            showNoContentLayout();
        }

        int itemCount = analystReplyAdapter.getItemCount();
        if (itemCount <= 0) {
            mListView.setNoMore(false);
            mListView.hideFooter();
        } else {
            mListView.setNoMore(!request.hasNextPage());
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setEmptyView(RecyclerView rv) {
        //这里，如果选择把事件吃掉，那么listView也就滑不动了，特别注意，这里不能返回true
//        rv.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });
        rv.setAdapter(new EmptyAdapter());
    }

    private class EmptyAdapter extends RecyclerView.Adapter<EmptyHolder> {

        @Override
        public EmptyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = View.inflate(getContext(), R.layout.item_analyst_empty_reply, null);
            return new EmptyHolder(itemView);
        }

        @Override
        public void onBindViewHolder(EmptyHolder holder, int position) {
        }

        @Override
        public int getItemCount() {
            return 3;
        }

    }

    private class EmptyHolder extends RecyclerView.ViewHolder {
        EmptyHolder(View itemView) {
            super(itemView);
        }
    }

    // 刚进入页面的时候，如果是加载缓存数据，必须检查当前网络是否可用，如果不可用，就要弹窗提醒
    private void toastWhenFirstLoad() {
        if (!NetUtil.isNetworkAvailable(getContext()))//如果有网络,然而还是失败，就显示异常布局
        {
            showListView();
            new ToastPopWindow(getContext(), getContext().getString(R.string.network_msg)).show();
        }
    }

    /**
     * 当请求失败时
     */
    private void onFailed() {
        // 判断当前网络是否正常，如果正常，就显示 error布局，否则就提示网络异常tip
        if (NetUtil.isNetworkAvailable(getContext()))//如果有网络,然而还是失败，就显示异常布局
            showNetErrorLayout();
        else {//如果没网络，就弹窗
            showListView();
            new ToastPopWindow(getContext(), getContext().getString(R.string.network_msg)).show();
        }
    }

    private void showListView() {
        ll_error.setVisibility(View.GONE);
        ll_no_content.setVisibility(View.GONE);
        mListView.setVisibility(View.VISIBLE);
    }

    private void showNetErrorLayout() {
        ll_error.setVisibility(View.VISIBLE);
        ll_no_content.setVisibility(View.GONE);
        mListView.setVisibility(View.GONE);
    }

    private void showNoContentLayout() {
        ll_error.setVisibility(View.GONE);
        ll_no_content.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.GONE);
    }
}
